package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishMapper dishMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveWithDish(SetmealDTO setmealDTO) {
        // 将setmealDTO转为Setmeal，并插入到setmeal表
        Setmeal setmeal = BeanUtil.copyProperties(setmealDTO, Setmeal.class);
        setmeal.setStatus(StatusConstant.DISABLE);
        setmealMapper.insert(setmeal);

        // 获取setmealDTO中的setmealDishes(套餐和菜品关系列表)，插入到setmeal_dish表（套餐菜品关系表）
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();

        // 设置setmealDishes中每一项的新插入的套餐id
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmeal.getId());
        });
        setmealDishMapper.insertBatch(setmealDishes);
    }

    @Override
    public PageResult pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());
        Page<SetmealVO> setmealVOS = setmealMapper.pageQuery(setmealPageQueryDTO);
        return new PageResult(setmealVOS.getTotal(), setmealVOS.getResult());
    }

    @Override
    public SetmealVO selectByIdWithDishes(Long id) {
        // 根据id查询套餐表信息
        Setmeal setmeal = setmealMapper.selectById(id);
        SetmealVO setmealVO = BeanUtil.copyProperties(setmeal, SetmealVO.class);

        // 根据分类id查询分类名称
        Category category = categoryMapper.selectById(setmealVO.getCategoryId());
        String categoryName = category.getName();
        setmealVO.setCategoryName(categoryName);

        // 根据套餐id查询与套餐关联的菜品
        List<SetmealDish> setmealDishes = setmealDishMapper.selectBySetmealId(id);
        setmealVO.setSetmealDishes(setmealDishes);
        return setmealVO;
    }

    /**
     * 起售或者禁售套餐
     * @param id
     * @param status
     */
    @Override
    public void startOrStop(Long id, Integer status) {
        // 套餐内如果有停售菜品则无法起售，抛出异常
        // 根据套餐id查询有哪些关联的菜品id
        if (StatusConstant.ENABLE.equals(status)){
            List<SetmealDish> setmealDishes = setmealDishMapper.selectBySetmealId(id);

            // 起售套餐时，根据菜品id列表查询其状态，如果存在菜品处于禁售状态则抛出异常
            List<Dish> dishes = dishMapper.selectByIds(setmealDishes.stream().map(SetmealDish::getDishId).collect(Collectors.toList()));
            dishes.forEach(dish -> {
                if (dish.getStatus().equals(StatusConstant.DISABLE)){
                    throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                }
            });
        }

        // 根据id设置套餐的状态
        Setmeal setmeal = Setmeal.builder().id(id).status(status).build();
        setmealMapper.update(setmeal);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(List<Long> ids) {
        // 遍历ids，根据id查询对应的status，如果存在套餐处于起售状态，则不允许删除，抛出异常
        for (Long id : ids) {
            Setmeal setmeal = setmealMapper.selectById(id);
            if (setmeal.getStatus().equals(StatusConstant.ENABLE)){
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        }

        // 根据ids删除套餐
        setmealMapper.deleteByIds(ids);

        // 根据ids删除套餐菜品关联项
        setmealDishMapper.deleteBySetmealIds(ids);
    }

    /**
     * 修改套餐，涉及套餐表和套餐菜品关系表的修改
     * @param setmealDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateWithDishes(SetmealDTO setmealDTO) {
        // setmealDTO转setmeal，修改套餐表
        Setmeal setmeal = BeanUtil.copyProperties(setmealDTO, Setmeal.class);
        setmealMapper.update(setmeal);

        // 根据套餐id删除套餐菜品关系表的相关项，再将新的项插入
        setmealDishMapper.deleteBySetmealIds(new ArrayList<>(Collections.singletonList(setmealDTO.getId()))); // 删除之前的

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if (setmealDishes != null && setmealDishes.size() > 0){
            setmealDishes.forEach(setmealDish -> {
                setmealDish.setSetmealId(setmeal.getId());
            });
            setmealDishMapper.insertBatch(setmealDishes);
        }

    }

    @Override
    public List<Setmeal> selectByCategoryId(Long categoryId) {
        return categoryMapper.selectByCategoryId(categoryId);
    }

    /**
     * 根据套餐id查询包含的菜品
     * @param id
     * @return
     */
    @Override
    public List<DishItemVO> selectDishesBySetmealId(Long id) {
        // 根据套餐id查询包含的菜品id
        List<SetmealDish> setmealDishes = setmealDishMapper.selectBySetmealId(id);

        List<Dish> dishes = new ArrayList<>();
        // 如果该套餐包含菜品则查询菜品的详细信息
        if (setmealDishes != null && !setmealDishes.isEmpty()){
            dishes = dishMapper.selectByIds(setmealDishes.stream().map(SetmealDish::getDishId).collect(Collectors.toList()));
        }
        // Dish转DishItemVO
        List<DishItemVO> dishItemVOS = BeanUtil.copyToList(dishes, DishItemVO.class);

        // 设置dishItemVOS的copies属性
        for (int i = 0; i < dishItemVOS.size(); i++) {
            if (setmealDishes != null) {
                dishItemVOS.get(i).setCopies(setmealDishes.get(i).getCopies());
            }
        }
        return dishItemVOS;
    }
}
